package com.fa.wisdom.ui.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.coder.zzq.smartshow.dialog.LoadingDialog;
import com.fa.wisdom.R;
import com.fa.wisdom.adapter.HomeMenuAdapter;
import com.fa.wisdom.base.BaseFragment;
import com.fa.wisdom.base.Constant;
import com.fa.wisdom.base.LazyLoadBaseFragment;
import com.fa.wisdom.listen.TopSmoothScroller;
import com.fa.wisdom.model.HomeENTITY;
import com.fa.wisdom.model.HomeGroupEntity;
import com.fa.wisdom.model.ResultEntity;
import com.fa.wisdom.net.MyCallback;
import com.fa.wisdom.net.Task;
import com.fa.wisdom.ui.AddHomeActivity;
import com.fa.wisdom.ui.MainActivity;
import com.fa.wisdom.ui.NoScrollViewPager;
import com.fa.wisdom.ui.PublicFragment;
import com.fa.wisdom.ui.QRConfigActivity;
import com.fa.wisdom.ui.ScanActivity;
import com.fa.wisdom.utils.Loading;
import com.fa.wisdom.utils.ScreenUtil;
import com.fa.wisdom.utils.SpUtils;
import com.fa.wisdom.utils.ToastUtils;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import retrofit2.Response;

public class HomeFragment extends BaseFragment {
    View statusBarPlace;
    AppCompatSpinner spinner;
    ImageView iv_click;
    ImageView iv_add;
    RecyclerView recyclerView;
    HomeMenuAdapter homeMenuAdapter;
    List<HomeGroupEntity> homeGroupEntities;
    RelativeLayout ll_manager_home;
    NoScrollViewPager viewPager;
    ImageView iv_msg;
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onGetMessage(Object msg) {
        String data = String.valueOf(msg);
        if (data.equals("refresh")) {
            getMyGroup();
        }
    }

    @SuppressLint("InflateParams")
    @Override
    public View setContentView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_home, null);
    }

    //根据二维码扫出来的值判断设备
    private void checkDevice(String qrContent) {
        LoadingDialog dialog = Loading.getInstance().onShowLargeLoading("加载中...");
        dialog.showInActivity(requireActivity());
        int userID = SpUtils.getInstance().decodeInt(Constant.User_id, -1);
        String token = SpUtils.getInstance().decodeString(Constant.TOKEN, "");
        OkHttpUtils.get().url("https://br.feiaikeji.cn/index.php/api/device/get_device_info")
                .addParams("device_code", qrContent)
                .addParams("user_id", String.valueOf(userID))
                .addParams("token", token)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                dialog.dismiss();
                ToastUtils.showError("识别失败");
            }

            @Override
            public void onResponse(String response, int id) {
                dialog.dismiss();
                JSONObject jo = JSON.parseObject(response);
                if (jo.containsKey("data")) {
                    int type = jo.getJSONObject("data").getInteger("type");
                    if (type == 2) {//表示摄像头
                        startActivity(new Intent(requireActivity(), QRConfigActivity.class));
                    } else {//其他设备  怎么添加

                    }
                } else {
                    ToastUtils.showError("请在管理端添加该设备");
                }

                Log.e("test-data", "onResponse: " + response);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EventBus.getDefault().register(this);
        iv_msg=view.findViewById(R.id.iv_msg);
        viewPager = view.findViewById(R.id.viewPager);
        statusBarPlace = view.findViewById(R.id.view_status_bar_place);
        ll_manager_home = view.findViewById(R.id.ll_manager_home);
        recyclerView = view.findViewById(R.id.recycle);
        spinner = view.findViewById(R.id.spinner);
        iv_click = view.findViewById(R.id.iv_click);
        iv_add = view.findViewById(R.id.iv_add);
        ViewGroup.LayoutParams params = statusBarPlace.getLayoutParams();
        params.height = ScreenUtil.getStatusBarHeight(getContext());
        statusBarPlace.setLayoutParams(params);
        iv_click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                startActivity(new Intent(requireActivity(), QRConfigActivity.class));
            }
        });
        iv_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(requireActivity(), new String[]{Manifest.permission.CAMERA}, 1);
                    return;
                }
                startActivityForResult(new Intent(requireActivity(), ScanActivity.class), 888);
            }
        });
        List<String> titles = new ArrayList<>();
        homeGroupEntities = new ArrayList<>();
        titles.add("全部");
        titles.add("主卧");
        titles.add("次卧");
        titles.add("客厅");
        titles.add("厨房");
        titles.add("阳台");
        titles.add("儿童房");
        titles.add("卫生间");
        for (int i = 0; i < titles.size(); i++) {
            HomeGroupEntity homeGroupEntity = new HomeGroupEntity();
            homeGroupEntity.setSelect(i == 0);
            homeGroupEntity.setTitle(titles.get(i));
            homeGroupEntities.add(homeGroupEntity);
        }
        homeMenuAdapter = new HomeMenuAdapter(homeGroupEntities);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(requireActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setHasFixedSize(false);
        recyclerView.setAdapter(homeMenuAdapter);
        TopSmoothScroller smoothScroller = new TopSmoothScroller(requireContext());
        homeMenuAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                homeGroupEntities.get(position).setSelect(true);
                for (int i = 0; i < homeGroupEntities.size(); i++) {
                    if (i != position) {
                        homeGroupEntities.get(i).setSelect(false);
                    }
                }
                homeMenuAdapter.notifyDataSetChanged();
                smoothScroller.setTargetPosition(position);
                linearLayoutManager.startSmoothScroll(smoothScroller);
                viewPager.setCurrentItem(position);
            }
        });
        ll_manager_home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转添加home管理页面
                requireActivity().startActivity(new Intent(requireActivity(), AddHomeActivity.class)
                        .putExtra("homeID", homeID));
            }
        });
        iv_msg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((MainActivity)requireActivity()).getTabLayout().setCurrentTab(3);
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1 && grantResults.length == 1) {
            boolean hasPermissionDismiss = false;//有权限没有通过
            if (1 == requestCode) {
                for (int grantResult : grantResults) {
                    if (grantResult == -1) {
                        hasPermissionDismiss = true;
                        break;
                    }
                }
            }
            if (!hasPermissionDismiss) {
                startActivityForResult(new Intent(requireActivity(), ScanActivity.class), 888);
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            Bundle bundle = data.getExtras();
            if (bundle == null) {
                return;
            }
            if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                String result = bundle.getString(CodeUtils.RESULT_STRING);
                checkDevice(result);
            } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                ToastUtils.showError("识别失败，请重新扫描");
            }
        }
    }

    private boolean isFirst = true;

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (isFirst) {
                isFirst = false;
                getMyGroup();
            }
        }
    }

    List<HomeENTITY> homeENTITYList = new ArrayList<>();

    private int homeID;

    //获取我的分组
    private void getMyGroup() {
        int userID = SpUtils.getInstance().decodeInt(Constant.User_id, -1);
        String token = SpUtils.getInstance().decodeString(Constant.TOKEN, "");
        Task.getApiService().getMyGroup(0, userID, token).enqueue(new MyCallback<ResultEntity>() {
            @Override
            protected void onSuccess(Response<ResultEntity> response) {
                String jsonString = JSON.toJSONString(response.body());
                JSONObject jsonObject = JSON.parseObject(jsonString);
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                if (homeENTITYList != null)
                    homeENTITYList.clear();
                else
                    homeENTITYList = new ArrayList<>();
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                    int id = jsonObject1.getInteger("pid");
                    HomeENTITY homeENTITY = new HomeENTITY();
                    homeENTITY.setId(id);
                    homeENTITY.setGroup_id(jsonObject1.getInteger("id"));
                    homeENTITY.setName(jsonObject1.getString("name"));
                    homeENTITYList.add(homeENTITY);
                }
                String[] array = new String[homeENTITYList.size()];
                for (int i = 0; i < homeENTITYList.size(); i++) {
                    array[i] = homeENTITYList.get(i).getName();
                }
                ArrayAdapter<String> deviceAdapter =
                        new ArrayAdapter<String>(requireActivity(), R.layout.spinner_item, array);
                //设置下拉列表的风格,simple_spinner_dropdown_item是android系统自带的样式，等会自定义修改
                deviceAdapter.setDropDownViewResource(R.layout.dropdown_stytle);

                spinner.setAdapter(deviceAdapter);

                spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        //选择了某一项
                        homeID = homeENTITYList.get(position).getId();
                        int groupId = homeENTITYList.get(position).getGroup_id();
                        SpUtils.getInstance().encode("group_id", groupId);
                        getMyGroupContent(groupId);
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    //获取我的分组
    private void getMyGroupContent(int pid) {
        int userID = SpUtils.getInstance().decodeInt(Constant.User_id, -1);
        String token = SpUtils.getInstance().decodeString(Constant.TOKEN, "");
        Task.getApiService().getMyGroupContent(userID, pid, token).enqueue(new MyCallback<ResultEntity>() {
            @Override
            protected void onSuccess(Response<ResultEntity> response) {
                String jsonString = JSON.toJSONString(response.body());
                JSONObject jsonObject = JSON.parseObject(jsonString);
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                if (homeGroupEntities != null)
                    homeGroupEntities.clear();
                else
                    homeGroupEntities = new ArrayList<>();
                HomeGroupEntity homeENTITY_1 = new HomeGroupEntity();
                homeENTITY_1.setId(pid);
                homeENTITY_1.setTitle("全部");
                homeENTITY_1.setSelect(true);
                homeGroupEntities.add(homeENTITY_1);
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                    int id = jsonObject1.getInteger("id");
                    HomeGroupEntity homeENTITY = new HomeGroupEntity();
                    homeENTITY.setId(id);
                    homeENTITY.setTitle(jsonObject1.getString("name"));
                    homeENTITY.setSelect(false);
                    homeGroupEntities.add(homeENTITY);
                }
                homeMenuAdapter.notifyDataSetChanged();
                if (mFragments == null) {
                    mFragments = new ArrayList<>();
                } else {
                    mFragments.clear();
                }
                for (int i = 0; i < homeGroupEntities.size(); i++) {
                    mFragments.add(new PublicFragment(homeGroupEntities.get(i).getId(), i));//0
                }
                viewPager.setAdapter(new MyPagerAdapter(getChildFragmentManager()));
                viewPager.setCurrentItem(0);
                viewPager.setOffscreenPageLimit(mFragments.size() - 1);
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    private List<Fragment> mFragments;

    //这里用了内部类自定义viewpager的适配器
    class MyPagerAdapter extends FragmentPagerAdapter {

        MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        /**
         * 返回数据的总个数
         *
         * @return 总个数
         */
        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public Fragment getItem(int i) {
            return mFragments.get(i);
        }


    }
}
